package com.dreamwhale.machinery.pay.weChat.utils;


import com.dreamwhale.machinery.pay.weChat.config.WeChatConfig;
import com.dreamwhale.machinery.wxConfig.WechatConfig;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.jdom2.JDOMException;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class PrepayIdRequestHandler extends RequestHandler {


    public PrepayIdRequestHandler(HttpServletRequest request,
                                  HttpServletResponse response) {
        super(request, response);
    }

    public String createMD5Sign() {
        StringBuilder sb = new StringBuilder();
        Set es = super.getAllParameters().entrySet();
        for (Object e : es) {
            Map.Entry entry = (Map.Entry) e;
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if (v == null || v.equals("")) continue;
            sb.append(k).append("=").append(v).append("&");
        }
        String params = sb.append("key=" + WeChatConfig.APP_KEY).substring(0);
        String sign = Md5Util.MD5Encode(params, "utf8");
        return sign.toUpperCase();
    }

    // 提交预支付
    public String sendPrepay() throws JDOMException, IOException {
        String prepayid = "";
        Iterator it = super.getAllParameters().entrySet().iterator();
        StringBuilder sb = new StringBuilder("<xml>");
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            sb.append("<").append(k).append(">").append(v).append("</").append(k).append(">");
        }
        sb.append("</xml>");
        String params = sb.substring(0);
        System.out.println("请求参数：" + params);
        String requestUrl = super.getGateUrl();
        System.out.println("请求url：" + requestUrl);
        TenpayHttpClient httpClient = new TenpayHttpClient();
        httpClient.setReqContent(requestUrl);
        String resContent = "";
        if (httpClient.callHttpPost(requestUrl, params)) {
            resContent = httpClient.getResContent();
            System.out.println("获取prepayid的返回值：" + resContent);
            Map map = XMLUtil.doXMLParse(resContent);
            if (map != null && map.containsKey("prepay_id"))
                prepayid = map.get("prepay_id").toString();
        }
        return prepayid;
    }

    public Map sendHttpsPrepay() throws JDOMException, IOException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyManagementException {

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        //这里自行实现我是使用数据库配置将证书上传到了服务器可以使用 FileInputStream读取本地文件

        File file = new File("C:/apiclient_cert.p12");
        FileInputStream fileInputStream = new FileInputStream(file);
        try {
            //这里写密码..默认是你的MCHID
            keyStore.load(fileInputStream, WechatConfig.mch_id.toCharArray());
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } finally {
            fileInputStream.close();
        }
        SSLContext sslcontext = SSLContexts.custom()
                //这里也是写密码的
                .loadKeyMaterial(keyStore, WechatConfig.mch_id.toCharArray())
                .build();


        String prepayid = "";
        Iterator it = super.getAllParameters().entrySet().iterator();
        StringBuilder sb = new StringBuilder("<xml>");
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            sb.append("<").append(k).append(">").append(v).append("</").append(k).append(">");
        }
        sb.append("</xml>");
        String params = sb.substring(0);
        System.out.println("请求参数：" + params);
        String requestUrl = super.getGateUrl();
        System.out.println("请求url：" + requestUrl);
        TenpayHttpClient httpClient = new TenpayHttpClient();
        httpClient.setReqContent(requestUrl);
        String resContent = "";
        httpClient.httpsPostMethod(requestUrl, params.getBytes(), sslcontext);
        resContent = httpClient.getResContent();
        System.out.println("获取prepayid的返回值：" + resContent);
        return XMLUtil.doXMLParse(resContent);
//        sss
    }


}